package vivo

import (
	"crypto/hmac"
	"crypto/sha256"
	"dta-apk/global"
	"dta-apk/utils"
	"encoding/hex"
	"sort"
	"strconv"
	"strings"
)

func getSign(data map[string]string, key string) string {
	// 创建一个新的 HMAC-SHA256 对象
	h := hmac.New(sha256.New, []byte(key))

	// 写入要签名的数据
	h.Write([]byte(getUrlParamsFromMap(data)))

	// 计算签名结果
	signature := h.Sum(nil)

	// 将签名结果转换为十六进制字符串
	signatureHex := hex.EncodeToString(signature)

	return signatureHex
}

func getUrlParamsFromMap(paramMap map[string]string) string {
	// 提取map的所有键
	keys := make([]string, len(paramMap))
	i := 0
	for key := range paramMap {
		keys[i] = key
		i++
	}
	params := []string{}
	// 按键的ASCII码进行排序
	sort.Strings(keys)
	for _, key := range keys {
		if key != "sign" {
			temp_param := key + "=" + paramMap[key]
			params = append(params, temp_param)
		}
	}
	// 使用&拼接
	url := strings.Join(params, "&")

	return url
}

/*
获取公共参数
*/
func getCommonParam(method string) commonParam {
	commonParam := commonParam{
		Method:         method,
		Access_key:     global.Config.App.Vivo.AccessKey,
		Timestamp:      strconv.FormatInt(utils.TimeStampMilli(), 10),
		Format:         "json",
		V:              "1.0",
		Sign_method:    "hmac",
		Target_app_key: "developer",
	}
	return commonParam
}
